<?php
function resizeImage($file, $w, $h, $ouput){
	
	$resize = new Resize($file);
	$resize -> resizeImage($w, $h, 'exact');

	$ext=getExtension($file);
	$resize -> saveImage($ouput.".$ext", 100);
	
	$fileName = getFileNameFromDirec($ouput).'.'.$ext;
	return $fileName;
}
function makeThumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)){
	$src_img=imagecreatefromjpeg($img_name);
}
if(!strcmp("png",$ext)){
	$src_img=imagecreatefrompng($img_name);
}

//gets the dimmensions of the image
$old_x=imagesx($src_img);
$old_y=imagesy($src_img);

$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2)	{
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else	{
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext)){
	imagepng($dst_img,$filename);
}else{
	imagejpeg($dst_img,$filename,95); 
}

//destroys source and destination images. 
imagedestroy($dst_img); 
imagedestroy($src_img); 
}
function getFileNameFromDirec($str){
$i = strrpos($str,"/");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$file = substr($str,$i+1,$l);
return $file;
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function formatPrice($price){
	$str = (string)$price;
	$len = strlen($str);

	$strResult = '';
	for($a = 0; $a<$len; $a++){
		$b = $len-$a;
		if($b%3==0 && $a!=0){
			$strResult  .= ',';
		}
		$strResult .=$str[$a]; 
	}
	return $strResult;
}
function recursiveMenu($sourceArr=array(),$Link=null, $parent=0,$urlAjax, &$newMenu){
	
	if(count($sourceArr)>0){
		$newMenu .= '<ul id="treeView">';
		foreach($sourceArr as $key=>$value){
			if($value['parent_id'] == $parent){
				if($Link==null){
					$newMenu .= '<li><a onclick="showInfoToForm('.$value['category_id'].', \''.$urlAjax.'\')">'.$value['category_name'] .'</a>';
				}else{
					$newMenu .= '<li><a href="'.$Link.'='.$value['category_id'].'">'.$value['category_name'] .'</a>';
				}
				$newParents = $value['category_id'];
				unset($sourceArr[$key]);
				recursiveMenu($sourceArr,$Link, $newParents, $urlAjax, $newMenu);
				$newMenu .= '</li>';
			}
		}
		$newMenu .= '</ul>';
		
	}
}
function creatTree($arrSource,$urlAjax, $Link=null, $parents=0){
	recursiveMenu($arrSource,$Link, $parents=0, $urlAjax, &$newMenu);
	return str_replace('<ul id="treeView"></ul>','',$newMenu);
}
function creatButton($link = '#', $imgSrc, $option=null){
	$html = "<a href='" . $link . "'>";
	if($option['func']){
		$html = "<a href='#' onclick='" . $option['func'] . "'> ";
	}
	$html .= "<img src='" . $imgSrc . "' title='" . $option['title'] . "' />";
	$html .= '</a>';
	return $html; 
}
/*$arr2 la mang 1 chieu*/
function getArraytoString($arr){
	$str="";
	if(count($arr)>0){
		$str = @implode(',',$arr);
	}
	return $str;
}

function setHeader($file_name){
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=$file_name");
		header("Pragma: no-cache");
		header("Expires: 0");
	}
function limitContentByWord($str, $limit){
                $str = trim($str);
                $count=1;
                for($i=0; $i<strlen($str); $i++){
                        if(($str[$i]==" ") && ($str[$i+1] != " ")){
                                $count++;
                        }
                        if($count == ($limit+1)){
                                $str = substr($str,0, $i);
                        }
                }
                return $str.'...';
} 
function check_user_login($session){
	if(READ_SESSION($session)){
		return true;
	}else{
		return false;
	}
}
function getFileNameToArr($dir,$extension,$option=true){
	$dh = opendir($dir);
	if($dh==false){echo "Can not open this directory"; return false;}
	$arr = array();
	while($file = readdir($dh)){
		if($file !='.' && $file !='..'){
			if($option==true)
				$arr[] = str_replace($extension,"",trim($file));
			else
				$arr[] = trim($file);
		}	
	}
	closedir($dh);
	return $arr;
}
function convertContent($str){
	return str_replace("|","",$str);
}
function getFileToArr($dir, $separator){
	if(!file_exists($dir)){
		return 1;
	}else{
		$content = file_get_contents($dir);
		$arr = explode($separator,$content);
		return $arr;
	}
}

function limitContent($string, $limit){
	if(strlen($string)>$limit){
		$string = substr($string,0,$limit).'...';
		return $string;
	}else{
		return $string;
	}
}
function check_user($session_name, $url){
	if(!READ_SESSION($session_name)){
		redir($url);
		exit();
	}
}
function check_role($session_role,$urlRedir){
	if($_SESSION[$session_role]!=1){
		redir($urlRedir);
	}
}
function comboboxNumber($name, $min, $max, $seleted = null, $style=null, $header=null){
	$select = "<select name = '$name' class='$style'>";
	if($header != null){
		$select .="<option value='' selected='selected'>$header</option>";
	}
	for($i=$min; $i<=$max; $i++){
		if($i<10){
			if($i == $seleted){
				$select .="<option value='0$i' selected='selected'>0".$i."</option>";
				
			}else{
				$select .="<option value='0$i'>0".$i."</option>";
			}
		}else{
			if($i == $seleted){
				$select .="<option value='$i' selected='selected'>".$i."</option>";
				
			}else{
				$select .="<option value='$i'>".$i."</option>";
			}
		}
	}
	$select .="</select>";
	return $select;
}

function getComboNumber($name, $min, $max,$header=null,$style=null, $selected=null){
	$select = "<select name = '$name' class='$style'>";
	if($header != null){
		$select .="<option value='-1' selected='selected'>$header</option>";
	}
	for($i=$min; $i<=$max; $i++){
		if($selected != null){
			$select .="<option value='$i' selected='selected'>".$i."</option>";
		}else{
			$select .="<option value='$i'>".$i."</option>";
		}
	}
	$select .="</select>";
	$v=_POST($name);
	$select=str_replace("<option value='$v'>","<option value='$v' selected='selected'>",$select);
	return $select;
}

function getComboNormalf($name, $arr, $selected=null,$header=null, $eventhand=null,$style=null){
	$select = "<select name = '$name' $eventhand $style>";
	if($header != null){
		$select .="<option value='' selected='selected'>$header</option>";
	}
	foreach($arr as $key=>$value){
		if($key == $selected){
			$select .="<option value='$key' selected='selected'>".$value."</option>";
			
		}else{
			$select .="<option value='$key'>".$value."</option>";
		}
	}
	$select .="</select>";
	return $select;
}

function getCombo($tableName, $fKey, $fValue,$comboName, $mes, $focus=null,$eventhand=null,$where=null, $class=null){
	global $db;
	$where=(isset($where))?$where:' 1=1 ';
	$Sql="SELECT ".$fKey." , ". $fValue." FROM ". $tableName." WHERE $where";
	$rs=$db->fetchAll($Sql);
	$combo="<select name =$comboName class='".$class."' $eventhand ><option value='-1' selected='selected' >$mes</option>";
	foreach($rs as $row){
		if($row[$fKey]==$focus){
			$combo.="<option value='".$row[$fKey]."' selected='selected'>".$row[$fValue]."</option>";
		}else{
			$combo.="<option value='".$row[$fKey]."'>".$row[$fValue]."</option>";
		}
	}
	$combo.="</select>";
	if($focus==null){
		$focus=_POST($comboName);
		$combo=str_replace("<option value='".$focus."'>","<option value='".$focus."' selected >",$combo);
	}
	return $combo;
}

function getComboArray($arr,$comboName,$mes=null, $class=null,$eventHand=null){
	$combo="<select name='".$comboName."' class='".$class."' $eventHand >";
	if($mes!=""){
		$combo.="<option value='-1'>".$mes."</option> ";
	}
	foreach($arr as $fkey=>$fvalue){
			$combo.="<option value='".$fkey."'>".$fvalue."</option>";
	}
	$combo.="</select>";
	$v=_POST($comboName);
	$combo=str_replace("<option value='".$v."'>","<option value='".$v."' selected='selected'>",$combo);
	return $combo;
}
function toPage($mes,$url=null){
	echo 	"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />	
			<script>alert('".$mes."');window.location.href='".$url."'</script>";
	//exit();
}
function closeWindow(){
	echo "<script>window.close();</script>";
}
/*function loginLogoutString()
{
	global $base_url;
	$selfURL=selfURL();
	if(READ_SESSION("session_user")!="") 
	$show_Login_Looout_String="<li><a href='".$base_url."myaccount/logout' > Logout</a></li><li><a href='".$base_url."myaccount/' >My Account</a></li><li><a href='".$base_url."myaccount/changepassword'>Change Password</a></li>";
	else
		$show_Login_Logout_String="<li><a href='".$base_url."login/?done=$selfURL' > Login</a></li>";
	
	return $show_Login_Logout_String;
}*/
/*
 *	Get current url 
 @  Created by Nguyen Duc Manh*/
function selfURL() { 
	$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; 
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); 
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']; 
} 
function refUrl(){
	return $_SERVER['HTTP_REFERER'];
}
function strleft($s1, $s2) 
{ 
	return substr($s1, 0, strpos($s1, $s2)); 
}
/**
 * Return a component of the current path.
 *
 * When viewing a page at the path "admin/content/types", for example, arg(0)
 * would return "admin", arg(1) would return "content", and arg(2) would return
 * "types".
 *
 * Avoid use of this function where possible, as resulting code is hard to read.
 * Instead, attempt to use named arguments in menu callback functions. See the
 * explanation in menu.inc for how to construct callbacks that take arguments.
 *
 * @param $index
 *   The index of the component, where each component is separated by a '/'
 *   (forward-slash), and where the first component has an index of 0 (zero).
 *
 * @return
 *   The component specified by $index, or NULL if the specified component was
 *   not found.
 */

function arg($index = NULL) {
	 global $base_url;
	 
	if (isset ($_GET['q'])) {
		$arguments = explode('/', $_GET['q']);
	} else {
		$arguments = explode('/', str_replace($base_url,'',selfRequestURI()));
	}
	if (!isset ($index)) {
		return $arguments;
	}
	if (isset ($arguments[$index])) {
		return $arguments[$index];
	}
}
function sendMail($fromname,$tomail,$subj,$body,$replyto=null){
	$mail			  = new PHPMailer();
	$mail->Mailer	  = "smtp";  
	$mail->CharSet    = 'utf-8';
	$mail->IsSMTP();
	$mail->FromName   = $fromname;
	$mail->SMTPAuth   = true;                 	 // enable SMTP authentication
	//$mail->SMTPSecure = "ssl"; 
	if($replyto!=null){
		$mail->AddReplyTo($replyto);                 // sets the prefix to the servier
	}
	$mail->Host       = "mail.studentworkvietnam.com";  // sets GMAIL as the SMTP server
	$mail->Port       = 25;	// set the SMTP port for the GMAIL server
	$mail->Username   = "support@studentworkvietnam.com";  	// GMAIL username
	$mail->Password   = "1q2w3e4r5t#";     	// GMAIL password
	$mail->From       = "support@studentworkvietnam.com";
	$mail->Subject    = $subj;
	$mail->WordWrap   = 5000; // set word wrap
	//send email
	$body= preg_replace('/\\\\/','', $body);
	$mail->MsgHTML($body);
	$mail->AddAddress($tomail);
	$mail->IsHTML(true);
	if($mail->Send()){
		return 1;
	}else{
		return 0;
	}
}
function selfRequestURI($addARG = "") {
	$s = empty ($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":" . $_SERVER["SERVER_PORT"]);
	$REQUEST_URI = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
	if (trim($addARG)) {
		$REQUEST_URI = str_replace(array (
			"?$addARG",
			"&$addARG"
		), array (
			'',
			''
		), $REQUEST_URI);
	}
	$addURL = $REQUEST_URI . ((strpos($REQUEST_URI, "?") === false) ? "?" : "&") . $addARG;
	return (trim($addARG) != "") ? $addURL : $REQUEST_URI;
}
function recordset($sql)
{
	if($sql)
	{
		$rs = execSQL($sql);
		$row =  mysql_fetch_array($rs);	
		return $row;
	}
}
function getBookId($length){
	settype($template, "string");
	$template = "1234567890";
    settype($length, "integer");
    settype($rndstring, "string");
    settype($a, "integer");
    settype($b, "integer");
    for ($a = 0; $a <= $length; $a++) 
	{
        $b = rand(0, strlen($template) - 1);
        $rndstring .= $template[$b];
    }
    return "GB".$rndstring;
	
}
function getRandomString($length) 
{
	settype($template, "string");
	$template = "ABCDEFGHIJKL#@MOPQRSUVWXYZ12345#@6789abcdefghijklmnopqrstuvwxyz#@";
    settype($length, "integer");
    settype($rndstring, "string");
    settype($a, "integer");
    settype($b, "integer");
    for ($a = 0; $a <= $length; $a++) 
	{
        $b = rand(0, strlen($template) - 1);
        $rndstring .= $template[$b];
    }
    return $rndstring;
}
/*
Name: converPost;
action:	Xoa bo cac ky tu trong lien nhau, ky tu trong o dau string va cuoi string
@author: Tuanlm
@result:string;
*/
function convertPost($str){
	if(is_array($str)){
		foreach ($str as $key => $value){
			$str[$key]=convertPost($str[$key]);
		}
	}
	else {
		if($str=="") return $str;
		$tem=array();
		$tem=explode(' ',$str);
		$n=count($tem);
		for($i=0;$i<$n;$i++){
			if($tem[$i]==""||$tem[$i]=="&nbsp;") unset($tem[$i]);
		}
		$str=implode(" ",$tem);
	}
	$str=str_replace("\\",'',$str);
	$str=str_replace("<?","",$str);
	$str=str_replace("<%","",$str);
	$str=str_replace("&lt;?","",$str);
	$str=str_replace("&lt;%","",$str);
	$str=str_replace("<script","",$str);
	$str=str_replace("&lt;script","",$str);
	return $str;
}
function _POST($value='')
{
	global $_GET, $_POST, $HTTP_POST_VARS,$HTTP_GET_VARS;
	if (isset($_POST["$value"]))
	{
		return convertPost(str_replace("'","&#039;",$_POST["$value"]));
	}
	elseif (isset($HTTP_POST_VARS["$value"]))
	{
	    return convertPost(str_replace("'","&#039;",$HTTP_POST_VARS["$value"]));
	}
	elseif (isset($_GET["$value"]))
	{
	    return convertPost(str_replace("'","&#039;",$_GET["$value"]));
	}
	elseif (isset($HTTP_GET_VARS["$value"]))
	{
	    return convertPost(str_replace("'","&#039;",$HTTP_GET_VARS["$value"]));
	}
	else
	{
	    return ;
	}
}
/**
 * This function create a page navigator of the list
 * @param  $page - The Posted/Get value of the current page
 * @param  $row_total - The total number of records of the list
 * @param  $page_size - The number of records displayed on each page
 * @param  $pagegroup_size - The number of page indexes displayed. Others will be visible when click on "Next xx pages" eg.
 * @param  $class - The class used in the page number
 * @param  $url - The navigation url
 * @return a table of navigation numbers for pages
 * @example $pages = pagenavigator(2,100,20,10,"$PHP_SELF?keyword=$keyword");
 modify by minhnvt1 7/12/2010
 */
function pagenavigator($page, $row_total, $page_size, $pagegroup_size,$url, $class=null) 
{
	$andpage=(strrpos ($url,"?")===false)?"?pi=":"&pi=";
	$page_total = floor(($row_total-1)/$page_size)+1;
	if(!$page || $page > $page_total || $page < 1)
	{
		$page = 1;
	}
	
	$group = floor(($page-1)/$pagegroup_size)+1;
	$start_page = (($group-1)*$pagegroup_size)+1;
	$end_page = $start_page+$pagegroup_size-1;
	if ($end_page>$page_total) 
	{
		$end_page = $page_total;
	}
	if ($page_total>1) 
	{
		$str='';
		if ($end_page>$pagegroup_size)
		{
			$start_group = $pagegroup_size;
		}
		else
		{
			$start_group = 0;
		}
		if ($page>2)
		{
			$str.= '<a href="'.$url.'&pi=1" > First </a>';
		}
		if ($group>1)
		{
			$str.= '<a href="'.$url.'&pi='.($page-1).'" > &lt;&lt;  </a>';
		}
		if($page!=1&&$page!=$page_total) {$str.= '<a href="'.$url.'&pi='.($page-1).'" > &lt;&lt; </a>';}
		for ( $i=$start_page ; $i <= $end_page ;$i++)
		{
			$j=$i+$page_size;
			$begin = ($i-1)*$page_size + 1;
			$end = $begin + $page_size - 1; 
			if ($i == $page)
			{
				$str.= "<a class='current'>$i</a>";
			}
			else
			{
				$str.= '<a href="'.$url.'&pi='.$i.'"> '.$i.'</a> ';
			}
		}
		if ($page_total-$end_page>$pagegroup_size)
		{
			$end_group = $pagegroup_size;
		}
		else
		{
			$end_group = $page_total-$end_page;
		}
		if ($page<$page_total)
		{
			$str.= '<a href="'.$url.'&pi='.($page+1).'" > &gt;&gt; </a>';
		}
		if ($page_total>2&&$page<$page_total)
		{
			$str.= '<a  href="'.$url.'&pi='.$page_total.'" > Last</a>';
		}
		/*$onchange = "onchange = 'window.location.href=".'$url&p=3'."'";
		$slt ="<select name='pagesoption' style='margin:0px 0px 0px 10px; padding:5px;' $onchange >";
		for($j=1; $j<=$page_total; $j++){
			
			if($j==$page){
				$slt .="<option value='$j' selected='selected'>".$j."</option>";
			}else{
				$slt .="<option value='$j'>".$j."</option>";
			}
		}
		$slt .="</select>";*/
		return $str;
	}	
}
/**
 * This function create a page navigator of the list use ajax
 * @param  $page - The Posted/Get value of the current page
 * @param  $row_total - The total number of records of the list
 * @param  $page_size - The number of records displayed on each page
 * @param  $pagegroup_size - The number of page indexes displayed. Others will be visible when click on "Next xx pages" eg.
 * @param  $class - The class used in the page number
 * @param  $url - The navigation url
 * @return a table of navigation numbers for pages
 * @example $pages = pageajx(2,100,20,10,"navigator","$PHP_SELF?keyword=$keyword");
 modify by tuanlm 6/10/2009
 */
function pageajx($page, $row_total, $page_size=20, $pagegroup_size=5,$class='pagination',$func,$navigate=true) {
	$page_total = floor(($row_total-1)/$page_size)+1;
	if(!$page || $page > $page_total || $page < 1){
		$page = 1;
	}
	if($page=='max') $page=$page_total;
	$group = floor(($page-1)/$pagegroup_size)+1;
	$start_page = (($group-1)*$pagegroup_size)+1;
	$end_page = $start_page+$pagegroup_size-1;
	if ($end_page>$page_total) {
		$end_page = $page_total;
	}
	if ($page_total>1) {
		$str='<div id="'.$class.'">';
		if ($end_page>$pagegroup_size){
			$start_group = $pagegroup_size;
		}else{
			$start_group = 0;
		}
		if ($page>2){
			$str.= '<a onclick="'.$func.'(1)" title="1"><a  id="'.$class.'" >1</a>';
		}
		if ($page>=3){
			$str.= '<a onclick="'.$func.'('.($page-1).')" >&lt;&lt;</a>';
		}
		for ( $i=$start_page ; $i <= $end_page ;$i++){
			$j=$i+$page_size;
			$begin = ($i-1)*$page_size + 1;
			$end = $begin + $page_size - 1; 
			if ($i == $page){
				$str.= "<a>$i</a>";
			}else{
				$str.= '<a onclick="'.$func.'('.$i.')>'.$i.'</a>';
			}
		}
		if ($page_total-$end_page>$pagegroup_size){
			$end_group = $pagegroup_size;
		}
		else{
			$end_group = $page_total-$end_page;
		}
		if ($page<$page_total-1){
			$str.= '<a onclick="'.$func.'('.($page+1).')">&gt;&gt;</a>';
		}
		if ($page_total>2&&$page<$page_total){
			$str.= '<a onclick="'.$func.'('.$page_total.')" title="'.$page_total.'">'.$page_total.'</a> ';
		}
		if($navigate==true){
			$i=1;
			$str.="<select name='page' style='padding:5px 7px;' onchange='changePage(this)'>";
			while($i<=$page_total){
				if($i!=$page){$str.="<option value='$i'>$i</option>";}
				else{$str.="<option selected='selected' value='$i'>$i</option>";}
				$i++;
			}
			$str.="</select>";
		}
		$str.="</div>";
		return $str;
	}	
}
function READ_SESSION($session_name) 
{
    return $_SESSION[$session_name];
}
function WRITE_SESSION($session_name, $session_value)
{
	$_SESSION[$session_name]=$session_value;
}
/**
 *@parameter	: $str:string
 *@return 		: get extention of file 
 *@author		: Kiennt
 *@Create date	: 25/3/2010
 *@Demo			: getExtent("ac.abc.docx") Return 'docx'
 */
function subLastWord($str){
	$str=substr($str,0,strrpos($str," ")+1);
	return $str;
}
function getExtent($str){
	$position=substr($str,strrpos($str,".")+1,strlen($str));
	return $position;
}
function getFileName($str){
	$position=substr($str,strrpos($str,"_")+1,strlen($str));
	return $position;
}
function getMesErr($err){
	echo"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script>alert('".$err."');</script>";
	return false;
}

function uploadConvertName($str){
	return preg_replace("/[\\\|\[\]\(\)\{\}\?\'\"\`\%\*\,\:\;\=\+\<\>\&\$\^\@\#\$\!\~\/]{1}/", "",$str);
}
 /**
   *@para		:$url image location uploaded
   *			,$file file in local
   *			,$alow_type is array extention allow upload
   *			,$maxsize is max filesize
   *@return 	:1 upload thanh công
   *        	 0 Không chấp nhận filetype
   *        	 2 file qua lớn
   *        	 -1 upload lỗi
   *@author		: Kiennt
   *@Create date: 25/3/2010 
   document array(opd, otp, sxi, sti, ppt, pot, odt, ott, sxw, stw, doc, docx, rtf, txt, sdw, vor, sdw, vor, pdb, html, htm, xml, psw, uot, pdf, chm, ods, ots, sxc, stc, xlsx, xls, xlt, pxl )
   images   array('jpeg', 'jpg','gif', 'png', 'pjpeg', 'bmp', 'x-png' )
   *Demo		:uploadfile(img/categories/,$_FILES['cat_img'], 1,1024000)  
   */

function uploadfile($url,$file,$alow=1,$maxsize=5120000){
	if($alow==1){
		$alow_type = array('jpeg', 'jpg','gif', 'png', 'pjpeg', 'bmp', 'x-png' );
	} else if ($alow==2) {
		$alow_type = array('opd', 'otp', 'sxi', 'sti', 'ppt', 'pot', 'odt', 'ott', 'sxw', 'stw', 'doc', 'docx', 'rtf', 'txt', 'sdw', 'vor', 'sdw', 'vor', 'pdb', 'html', 'htm', 'xml', 'psw', 'uot', 'pdf', 'chm', 'ods', 'ots', 'sxc', 'stc', 'xlsx', 'xls', 'xlt', 'pxl', 'rar', 'zip', 'jpeg', 'jpg','gif', 'png', 'pjpeg', 'bmp', 'x-png' );
	} else if($alow==3){
		$alow_type = array('opd', 'otp', 'sxi', 'sti', 'ppt', 'pot', 'odt', 'ott', 'sxw', 'stw', 'doc', 'docx', 'rtf', 'txt', 'sdw', 'vor', 'sdw', 'vor', 'pdb', 'html', 'htm', 'xml', 'psw', 'uot', 'pdf', 'chm', 'ods', 'ots', 'sxc', 'stc', 'xlsx', 'xls', 'xlt', 'pxl', 'rar', 'zip', 'jpeg', 'jpg','gif', 'png', 'pjpeg', 'bmp', 'x-png','jpeg', 'jpg','gif', 'png', 'pjpeg', 'bmp', 'x-png' );
	}else {
		return 0;
	}
	$_tmpfile=$file["tmp_name"];
	$_size=$file["size"];
	$_name=str_replace(" ","-",convertPost($file['name']));
	$_name=uploadConvertName($_name);
	$type=strtolower(getExtent($_name));
	$error="";
	if($_name!=""){
		
		if(!in_array($type,$alow_type)){
			 return 1;
		}	
			  
		else if($_size>$maxsize||$_size==0){
			return 2;
		}else {
			$_name="_".date("y-m-d-H-i-s")."_".$_name;
			$url=$url.$_name;
			//@chmod($url,0766);
			if(move_uploaded_file($_tmpfile,$url))
			{return $_name;}
			else {return -1;}
		}
	}
}
function downloadFile($file)
{
	$path = $_SERVER['DOCUMENT_ROOT']."/orderv2/files/"; // change the path to fit your websites document structure
	$fullPath = $path.$file;
	$path_parts = pathinfo($fullPath);
	header("Expires: 0");  
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  
	header("Cache-Control: no-store, no-cache, must-revalidate");  
	header("Cache-Control: post-check=0, pre-check=0", false);  
	header("Pragma: no-cache"); 
	header("Content-type: application/octet-stream");
	header("Content-disposition: filename=\"".$path_parts["basename"]."\"");
	header("Content-length: $fsize");
	header("Cache-control: private"); //use this to open files directly
	
}
/*
	*This fuction create a select tag data html from database
*/
function load_option($sql=null,$name=null,$name_id=null,$selected_id=null,$mes=null)
{
	$rs=execSQL($sql);
	$str='<select name="'.$name_id.'">';
	$str.="<option value=''>..:".$mes.":..</option>";
	while($row=mysql_fetch_array($rs))
	{
		if($row[$name_id]==$selected_id)
		{
			$str.="<option value='".$row[$name_id]."' selected='selected'>".$row[$name]."</option>";
		}
		else {$str.="<option value='".$row[$name_id]."'>".$row[$name]."</option>";}
	}
	$str.="</select>";
	return $str;
}
/*
	*This fuction create a select tag data html from database
*/
function load_checkbox($sql,$post_name,$value_name,$display_name,$num_of_row,$checked_array=null){
	$rs=execSQL($sql);
	$num=0;
	$str="<table>";
	while($row=mysql_fetch_array($rs)){
		if($num>=$num_of_row){
			$str.="<tr>";
		}
		$str.='<td style="width:auto;"><input type="checkbox" name="'.$post_name.'[]" value="'.$row[$value_name].'" />'.$row[$display_name].'</td>';
		$num++;
		if($num>=$num_of_row){
			$str.="</tr>";
			$num=0;
		}
	}
	$str.="</table>";
	if($checked_array){
		while($a=array_pop($checked_array)){
			$str=str_replace('value="'.$a.'"','value="'.$a.'" checked="checked"',$str);
		}
	}
	return $str;
}
/**
 * This function help redirect page
 * @param  $url - The url needed to be redirected to
 * @return N/A
 * @example redir("index.php");
 */
function redir($url)
{ 
	echo "<script language = javascript>window.location.href='".$url."'</script>";
	exit();
}
/**
 * This function return ready data for mySQL save from textbox, textarea
 * @param  $data - The inputted data
 * @return smooth data
 * @example formatDataForMySql("ab' c # e fg");
 */
function formatDataForMySql($data)
{
	$data=str_replace("$",'&#36;',$data);
	//$data=str_replace("\\",'',$data);
	$data=str_replace('"',"&quot;",$data);
	$data=str_replace("'","&#039;",$data);
	$data=str_replace("<script ",'',$data);
	$data=str_replace("<iframe ",'',$data);
	//return nl2br($data);
	return $data;
}
/**
 * This function return ready data for mySQL save from FCK Editor
 * @param  $data - The inputted data
 * @return smooth data
 * @example formatDataForFCK("ab' c # e fg");
 */
function formatDataForFCK($data)
{
	//$data=str_replace("$",'&#36;',$data);
	$data=str_replace("'","&#039;",$data);
	return $data;
}
function textSpecialChars($val)
{
	// source from http://quickwired.com/kallahar/smallprojects/php_xss_filter_function.php
	 $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);

	 $search = 'abcdefghijklmnopqrstuvwxyz';
	 $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	 $search .= '1234567890!@#$%^&*()';
	 $search .= '~`";:?+/={}[]-_|\'\\';

	 for ($i = 0; $i < strlen($search); $i++) {
	  $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);
	  $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val);
	 }

	 $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
	 $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	 $ra = array_merge($ra1, $ra2);
	 $found = true;
	 while ($found == true) {
	  $val_before = $val;
	  for ($i = 0; $i < sizeof($ra); $i++) {
	   $pattern = '/';
	   for ($j = 0; $j < strlen($ra[$i]); $j++) {
	    if ($j > 0) {
	     $pattern .= '(';
	     $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
	     $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
	     $pattern .= ')?';
	    }
	    $pattern .= $ra[$i][$j];
	   }
	   $pattern .= '/i';
	   $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2);
	   $val = preg_replace($pattern, $replacement, $val);
	   if ($val_before == $val) {$found = false;}
	  }
	 }
	 //$allowedtags = "<h1><h2><h3><h4><h5><h6><font><strong><em><ul><li><pre><b><i><u><a><hr><blockquote><span><div><img><ol><br><table><tr><td>";
	 $allowedtags = "<font><a><span><abbr><acronym><style><address><b><u><bdo><big><blockquote><br><caption><cite><code><col><colgroup><dd><del><dfn><div><dl><dt><em><h1><h2><h3><h4><h5><h6><hr><i><img><ins><kbd><li><ol><p><param><pre><q><samp><small><span><strong><sub><sup><table><tbody><td><tfoot><th><thead><tr><tt><ul><var>";
	 $cstring = strip_tags($val, $allowedtags);
	 //$cstring = filter_xss($val, array('font','a', 'span', 'abbr', 'acronym','style', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'ol', 'p', 'param', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var'));

	 return formatDataForFCK($cstring);
}
function validateURL($url)
{
	$pattern = "/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/";
	return (preg_match($pattern, $url)||$url=='');  
}
function validateTel($str)
{
	$tomach1="/^([0-9]{1}|\+[0-9]{1})[0-9]{4,18}[0-9]{1}$/";
	$tomach2="/^[0-9]{2,4}(-[0-9]{2,4}-[0-9]{2,4}-[0-9]{2,4}-| [0-9]{2,4} [0-9]{2,4} [0-9]{2,4} )[0-9]{2,4}$/";
	$tomach3="/^\+[0-9]{2,4}(-[0-9]{2,4}-[0-9]{2,4}-[0-9]{2,4}-| [0-9]{2,4} [0-9]{2,4} [0-9]{2,4} )[0-9]{2,4}$/";
	$tomach4="/^(\+[0-9]{2,4}|[0-9]{2,4})(-[0-9]{2,4}-[0-9]{2,4}-| [0-9]{2,4} [0-9]{2,4} )[0-9]{2,4}$/";
	$tomach5="/^(\+[0-9]{2,4}|[0-9]{2,4})(-[0-9]{2,4}-| [0-9]{2,4} )[0-9]{2,4}$/";
	$tomach6="/^\([0-9]{2,4}\)[0-9]{2,9}[0-9]{1}$/";
	if(str=='') return true;
	return (preg_match($tomach1,$str)||preg_match($tomach2,$str)||preg_match($tomach3,$str)||preg_match($tomach4,$str)||preg_match($tomach5,$str)||preg_match($tomach6,$str));	
}
function check_null($str)
{
	return $str!='';
}
function check_num($str)
{
	$tomach="/^[0-9]{0,1}[0-9]{0,1}$/";
	if(preg_match($tomach,$str))
		if($str>0) return true;
		else return false;
	return preg_match($tomach,$str);
}
function check_price($str)
{
	$tomach="/^[0-9]{0,1}[0-9]{1,8}[\.]{0,1}[0-9]{0,2}$/";
	if(preg_match($tomach,$str))
		if($str>0) return true;
		else return false;
	return preg_match($tomach,$str);
}
function html($html)
{
	$tomach="/(<script)||(<?)||(<%)||(<cf)/";
	return !preg_match($tomach,$html);
}
function check_login($condition=null){
	if($condition){
		if(READ_SESSION('a_permission')==$condition&&check_login()){
			return true;
		} else {
			return false;
		}
	}
	if(READ_SESSION('a_username')){
		return true;
	} else {
		return false;
	}
}
function start_login()
{
	global $base_url; 
	if (basename ($_SERVER['SCRIPT_FILENAME']))
	{
		redir($base_url."/administrator/login");
	}
}
function controller_hander($modules=null,$file=null,$arg=null){
	global $base_url;
	if(file_exists(CONTROLLER."/$modules.php")){
		include CONTROLLER."/$modules.php";
	}else if($modules==''||$modules =='index.php'||$modules =='index'){
		include CONTROLLER."/index.php";
	} else if(!file_exists(CONTROLLER."/$modules/$file.php")){
		$mid="Can't display page!";
	} else {
	//if($modules=='home') $modules='index';
		if(file_exists(CONTROLLER."/$modules/$file.php")){
			include CONTROLLER."/$modules/$file.php";
		} else {
			$file='list';
			include CONTROLLER."/$modules/index.php";
		}
	}
	return $mid;
}
//Made by Tuanlm, Quyna:
//this function change fomat date
//echo fomatdate('m/d/y','y-m-d','11/10/2009');
function fomatdate($infomat,$outfomat,$date){
	$infomat=strtolower($infomat);
	$outfomat=strtolower($outfomat);
	$indate=array();$indate=split('[/.-]',$infomat);
	$outdate=array();$outdate=split('[/.-]',$outfomat);
	$_date=array();$_date=split('[/.-]',$date);
	$return=array();
	for ($i=0;$i<=2;$i++)
		for ($j=0;$j<=2;$j++){
			if ($outdate[$i]==$indate[$j])
				$return[$i]=$_date[$j];
		}
	switch($outfomat){
		case 'd/m/y': $str=implode('/',$return); break;
		case 'm/d/y': $str=implode('/',$return); break;
		case 'y/m/d': $str=implode('/',$return); break;
		case 'y/d/m': $str=implode('/',$return); break;
		case 'd-m-y': $str=implode('-',$return); break;
		case 'm-d-y': $str=implode('-',$return); break;
		case 'y-m-d': $str=implode('-',$return); break;
		case 'y-d-m': $str=implode('-',$return); break;
		default: $str='error'; break;
	}
	unset($indate,$outdate,$_date,$return);
	return $str;
}
//Made by Tuanlm, Quyna:
//this function return different of two day with fomat day
//echo subtraction('d/m/y','20/11/2009','y-m-d','2009-11-21');
function subtraction($outfomat,$out_day,$infomat,$in_day){
	if($infomat!='m/d/y') {$in_day=fomatdate($infomat,'m/d/y',$in_day);}
	if($outfomat!='m/d/y') {$out_day=fomatdate($outfomat,'m/d/y',$out_day);}
	$time1=strtotime($in_day); 
	$time2=strtotime($out_day);
	$day=($time2-$time1)/86400;
	return $day;
}
function subTime($big,$small){
	$h1=split(':',$big);
	$h2=split(':',$small);
	return $h1[0]-$h2[0];
}
function subtraction1($out_day,$in_day){
	$time1=date("y-m-d",$in_day); 
	$time2=date("y-m-d",$out_day);
	$t1=mktime(0,0,0,date("m",$time1),date("d",$time1),date("y",$time1));
	$t2=mktime(0,0,0,date("m",$time2),date("d",$time2),date("y",$time2));
	$day=abs($t1-$t2)/8400;
	return $day;
}
function timediff($str1,$str2){
	$s1=split(":",$str1);
	$s2=split(":",$str2);
	return (($s1['0']-$s2['0'])*60+$s1['1']-$s2['1']);
}
function thisQuarter($number=false){
	if($number==true) { return ceil(date('m')/3);}
	switch (ceil(date('m')/3)){
		case 1: return 'I';break;
		case 2: return 'II';break;
		case 3: return 'III';break;
		case 4: return 'IV';break;
	}
}
function beginQuarter($quarter=null,$year=null,$number=false){
	if($number==false){
		switch ($quarter){
			case 'I': $quarter=1;break;
			case 'II': $quarter=2;break;
			case 'III': $quarter=3;break;
			case 'IV': $quarter=4;break;
		}
	}
	if($year==null){
		$year=date('Y');
	}
	switch ($quarter){
		case 1: return $year.'-01-01';break;
		case 2: return $year.'-04-01';break;
		case 3: return $year.'-07-01';break;
		case 4: return $year.'-10-01';break;
		default: return beginQuarter(thisQuarter());break;
	}
}
function endQuarter($quarter=null,$year=null,$number=false){
	if($number==false){
		switch ($quarter){
			case 'I': $quarter=1;break;
			case 'II': $quarter=2;break;
			case 'III': $quarter=3;break;
			case 'IV': $quarter=4;break;
		}
	}
	if($year==null){
		$year=date('Y');
	}
	switch ($quarter){
		case 1: return $year.'-03-31';break;
		case 2: return $year.'-06-30';break;
		case 3: return $year.'-09-31';break;
		case 4: return $year.'-12-31';break;
		default: return endQuarter(thisQuarter());break;
	}
}
function thisMonth(){
	return date('m');
}
function endMonth($month=null,$year=null){
	if($year==null){
		$year=date('Y');
	}
	if($month==null){
		$month=thisMonth();
	}
	if( in_array($month,array(1,3,5,7,8,10,12,'01','03','05','07','08'))){
		return "$year-$month-31";
	}
	if( in_array($month,array(4,6,9,11,'04','06','09'))){
		return "$year-$month-30";
	}
	if(in_array($month,array(2,'02'))){
		if(($year%4)==0){
			return "$year-$month-29";
		}else {
			return "$year-$month-28";
		}
	}
}
function beginMonth($month=null,$year=null){
	if($year==null){
		$year=date('Y');
	}
	if($month==null){
		$month=thisMonth();
	}
	return "$year-$month-01";
}
// made by Lê minh Tuấn
// regular expression \: html tag
// "/(\<[a-zA-Z\ ]{1,} ((|\ )*+[a-zA-Z\-\ ]+=(\"|\\')?[a-zA-Z0-9\;\:\#\(\)\/\.\-\_\$\!\@\%\^\&\*\=\+\{\}\[\]\|\?\,\~\`\ ]+(\"|\\')?+(|\ )*)*(\>|\/\>))|(\<\/[a-zA-Z\ ]{1,}\>)/"
function subHTML($str){
	return preg_replace("/(\<[a-zA-Z\ ]{1,} ((|\ )*+[a-zA-Z\-\ ]+=(\"|\\')?[a-zA-Z0-9\;\:\#\(\)\/\.\-\_\$\!\@\%\^\&\*\=\+\{\}\[\]\|\?\,\~\`\ ]+(\"|\\')?+(|\ )*)*(\>|\/\>))|(\<\/[a-zA-Z\ ]{1,}\>)|(\<[a-zA-Z\ ]{1,}\>)/", "",str_replace("&gt;",'>',str_replace("&lt;",'<',$str)));
}
function checkPre($str){
	if(check_login()==false){
		return 0;
	}
	$rs=execSQL("select tblrole.rol_code, u.use_email from tbluser as u left join tblpartner as p on u.par_id=p.par_id left join tbllocal as l on p.loc_id=l.loc_id left join tblresource as r on  u.res_id=r.res_id left join tblrole on r.rol_id=tblrole.rol_id where u.use_email='".$_SESSION['a_email']."' and tblrole.rol_code='$str' limit 1");
	if(mysql_fetch_array($rs)){
		return 1;
	}else {
		return 0;
	}
}
function getPre(){
	$rs=execSQL("select tblrole.rol_code, u.use_email from tbluser as u left join tblpartner as p on u.par_id=p.par_id left join tbllocal as l on p.loc_id=l.loc_id left join tblresource as r on  u.res_id=r.res_id left join tblrole on r.rol_id=tblrole.rol_id where u.use_email='".$_SESSION['a_email']."' limit 1");
	if($array=mysql_fetch_array($rs)){
	//print_r($array);
		return $array['rol_code'];
	}
}
function toUpper ($text) {
	$lower = array(
	'á','à','ả','ã','ạ','â','ấ','ầ','ậ','ẩ','ẫ','ă','ắ','ằ','ặ','ẵ','ẳ','ê','ế','ề','ệ','ể','ễ',
	'ô','ố','ồ','ộ','ổ','ỗ','ơ','ớ','ờ','ợ','ỡ','ở','ư','ứ','ừ','ự','ữ','ử','ị','ì','í','ĩ','ỉ',
	'ý','ỳ','ỵ','ỷ','ỹ','ù','ú','ụ','ũ','ủ'
	);
	
	$upper=array(
	'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','E','E','E','E','E','E',
	'O','O','O','O','O','O','O','O','O','O','O','O','U','U','U','U','U','U','I','I','I','I','I',
	'Y','Y','Y','Y','Y','U','U','U','U','U'
	);
	
	$text = str_replace($lower, $upper,$text);
	return strToUpper($text);
}
function toLower ($text) {
	$lower = array(
	'a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','e','e','e','ệ','e','e',
	'o','o','o','o','o','o','o','o','o','o','o','o','o','o','u','u','u','u','i','i','i','i','i',
	'y','y','y','y','y','u','u','u','u','u'
	);
	
	$upper=array(
	'Á','À','Ả','Ã','Ạ','Â','Ấ','Ầ','Ậ','Ẩ','Ẫ','Ă','Ắ','Ằ','Ặ','Ẵ','Ẳ','Ê','Ế','Ề','Ệ','Ể','Ễ',
	'Ô','Ố','Ồ','Ộ','Ổ','Ỗ','Ơ','Ớ','Ờ','Ợ','Ỡ','Ở','Ư','Ứ','Ừ','Ự','Ữ','Ử','Ị','Ì','Í','Ĩ','Ỉ',
	'Ý','Ỳ','Ỵ','Ỷ','Ỹ','Ù','Ú','Ụ','Ũ','Ủ');
	
	$text = str_replace($upper,$lower, $text);
	return strToLower($text);
}
function searchReplace($text){
	$unicode=array(
	'Á','À','Ả','Ã','Ạ','Â','Ấ','Ầ','Ậ','Ẩ','Ẫ','Ă','Ắ','Ằ','Ặ','Ẵ','Ẳ','Ê','Ế','Ề','Ệ','Ể','Ễ',
	'Ô','Ố','Ồ','Ộ','Ổ','Ỗ','Ơ','Ớ','Ờ','Ợ','Ỡ','Ở','Ư','Ứ','Ừ','Ự','Ữ','Ử','Ị','Ì','Í','Ĩ','Ỉ',
	'Ý','Ỳ','Ỵ','Ỷ','Ỹ','Ù','Ú','Ụ','Ũ','Ủ','Đ',
	'á','à','ả','ã','ạ','â','ấ','ầ','ậ','ẩ','ẫ','ă','ắ','ằ','ặ','ẵ','ẳ','ê','ế','ề','ệ','ể','ễ',
	'ô','ố','ồ','ộ','ổ','ỗ','ơ','ớ','ờ','ợ','ỡ','ở','ư','ứ','ừ','ự','ữ','ử','ị','ì','í','ĩ','ỉ',
	'ý','ỳ','ỵ','ỷ','ỹ','ù','ú','ụ','ũ','ủ','đ'
	);
	$text = str_replace($unicode,".*", $text);
	return strToLower($text);
}
function countValueInArray($value,$arr){
	$c=0;
	foreach($arr as $v){
		if($v){
			$v1=explode(',',$v);
		}
		foreach($v1 as $items){
			if($value==$items){$c++;}
		}
	}
	return $c;
}
?>